package com.atguigu.yygh.common.utils;

import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.sms.v20210111.SmsClient;
import com.tencentcloudapi.sms.v20210111.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse;
import com.tencentcloudapi.sms.v20210111.models.SendStatus;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class SmsUtil {

    /**
     * 腾讯云发送短信
     *
     * @param phone 手机号
     * @param code  验证码
     * @param time  过期时间
     */
    public static boolean sendMsg(String phone, String code, String time) throws TencentCloudSDKException {
        // 实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey
        String SecretId = "腾讯云账户SecretId";
        String SecretKey = "腾讯云账户SecretKey";
        Credential cred = new Credential(SecretId, SecretKey);

        // 实例化一个http选项，可选的，没有特殊需求可以跳过
        HttpProfile httpProfile = new HttpProfile();
        httpProfile.setEndpoint("sms.tencentcloudapi.com");

        // 实例化一个client选项，可选的，没有特殊需求可以跳过
        ClientProfile clientProfile = new ClientProfile();
        clientProfile.setHttpProfile(httpProfile);

        // 实例化要请求产品的client对象,clientProfile是可选的
        SmsClient client = new SmsClient(cred, "ap-beijing", clientProfile);

        // 实例化一个请求对象,每个接口都会对应一个request对象
        SendSmsRequest req = new SendSmsRequest();
        String[] phoneNumberSet1 = {"+86" + phone};
        req.setPhoneNumberSet(phoneNumberSet1);

        req.setSmsSdkAppId("1400518513");
        req.setSignName("朝月余晖");
        req.setTemplateId("950651");

        String[] templateParamSet1 = {code, time};
        req.setTemplateParamSet(templateParamSet1);

        // 返回的resp是一个SendSmsResponse的实例，与请求对象对应
        SendSmsResponse resp = client.SendSms(req);
        //解析返回结果
        SendStatus sendStatus = resp.getSendStatusSet()[0];
        if (sendStatus.getCode().equals("Ok")) {
            //成功
            return true;
        }

        //失败，记录错误日志
        log.error("发送短信出错：" + sendStatus.getMessage());
        return false;
    }
}
